package com.team.sion.service.Impl;

import com.team.sion.mapper.SingerMapper;
import com.team.sion.mapper.SongListMapper;
import com.team.sion.mapper.SongMapper;
import com.team.sion.pojo.*;
import com.team.sion.service.SingerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SingerServiceImpl implements SingerService {
    @Autowired
    private SingerMapper singerMapper;
    @Autowired
    private SongMapper songMapper;
    @Autowired
    private SongListMapper songListMapper;

    @Override
    public List<Singer> findAll() {
        SingerExample singerExample = new SingerExample();
//        singerExample.createCriteria().andSexEqualTo(sex);
        return singerMapper.selectByExample(singerExample);
    }

    @Override
    public List<Singer> findBySex(String sex) {
        SingerExample singerExample = new SingerExample();
        singerExample.createCriteria().andSexEqualTo(sex);
        return singerMapper.selectByExample(singerExample);
    }

    @Override
    public boolean addSinger(Singer singer) {
        SingerExample example = new SingerExample();
        example.createCriteria().andNameEqualTo(singer.getName());
        List<Singer> list = singerMapper.selectByExample(example);
        if (list.size() == 0) {
            singerMapper.insertSelective(singer);
            return true;
        }
        return false;
    }

    @Override
    public boolean updateSinger(Singer singer) {
        int i = singerMapper.updateByPrimaryKeySelective(singer);
        if (i == 1) {
            return true;
        }
        return false;
    }

    @Override
    public boolean deleteSinger(Integer id) {
        songMapper.closeForeignKey();

        SingerExample example = new SingerExample();
        example.createCriteria().andIdEqualTo(id);
        singerMapper.deleteByExample(example);

        SongExample sExample = new SongExample();
        sExample.createCriteria().andSingerIdEqualTo(id);
        songMapper.deleteByExample(sExample);

        List<Song> songList = songMapper.selectByExample(sExample);
        for (Song song : songList){
            songListMapper.deleteBySId(song.getId());
        }

        songMapper.openForeignKey();
        return true;

    }

    @Override
    public void updatePic(Integer id, String url) {
        Singer singer = singerMapper.selectByPrimaryKey(id);
        singer.setPic(url);
        singerMapper.updateByPrimaryKey(singer);
    }

}
